from .models import Users,QType,Question,Menu
from rest_framework import serializers

from django.contrib.auth.models import Group
from django.contrib.auth.hashers import make_password


# 菜单序列化器
class MenuModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Menu
        fields = '__all__'


# 角色序列化器
class GroupModelSerializer(serializers.ModelSerializer):
    # menu = serializers.SlugRelatedField(queryset=Menu.objects.all(),slug_field='path')
    menu = MenuModelSerializer(many=True)
    class Meta:
        model = Group
        fields = '__all__'


# 用户序列化器
class UsersModelSerializer(serializers.ModelSerializer):
    groups = serializers.SlugRelatedField(queryset=Group.objects.all(),slug_field='name',many=True)

    # 密码加密
    def validate_password(self,value):
        return make_password(value)

    def get_fields(self):
        data = super(UsersModelSerializer, self).get_fields()
        data['roleName'] = data['groups']
        return data

    class Meta:
        model = Users
        # 排除的字段 exclude无法和fields一起使用
        # exclude = ('password',)
        # 将password字段设置为只写
        extra_kwargs = {'password': {'write_only': True}}
        fields = '__all__'


# 题目序列化器
class QuestionModelSerializer(serializers.ModelSerializer):
    type = serializers.SlugRelatedField(queryset=QType.objects.all(),slug_field='title')
    class Meta:
        model = Question
        fields = '__all__'


# 题型序列化器
class QTypeModelSerializer(serializers.ModelSerializer):
    # children = QuestionModelSerializer(many=True,read_only=True)
    class Meta:
        model = QType
        fields = '__all__'




